package 数据结构和算法入门计划8月开始;
// https://leetcode-cn.com/problems/add-two-numbers/
public class 两数相加20820 {

      public class ListNode {
          int val;
          ListNode next;
          ListNode() {}
          ListNode(int val) { this.val = val; }
          ListNode(int val, ListNode next) { this.val = val; this.next = next; }
      }

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            // 课程 A -》 链表 -> 基础篇
            ListNode dummy = new ListNode();
            ListNode curr = dummy;
            int carry = 0;
            while (l1 != null || l2 != null) {
                int x = l1 == null ? 0 : l1.val;
                int y = l2 == null ? 0 : l2.val;

                int sum = x + y + carry;
                curr.next = new ListNode(sum % 10);
                // bug 修复：视频中忘了移动 curr 指针了
                curr = curr.next;
                carry = sum / 10;

                if (l1 != null) l1 = l1.next;
                if (l2 != null) l2 = l2.next;
            }
            if (carry != 0) curr.next = new ListNode(carry);
            return dummy.next;
        }
    }

}
